package com.nefu.editor.service.Impl;

import com.nefu.editor.core.mapper.WordCloudMapper;
import com.nefu.editor.core.model.WordCloud;
import com.nefu.editor.service.WordCloudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author chenchenT
 * @date : 18-11-13
 * @since : java 8
 */
@Service
public class WordCloudServiceImpl implements WordCloudService {

    private final WordCloudMapper wordCloudMapper;

    @Autowired
    public WordCloudServiceImpl(WordCloudMapper wordCloudMapper) {
        this.wordCloudMapper = wordCloudMapper;
    }

    @Override
    public int getRandom(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    @Override
    public int[] getRandoms(int min, int max, int count) {
        int[] randoms = new int[count];
        List<Integer> listRandom = new ArrayList<>();

        if (count > (max - min + 1)) {
            return null;
        }
        // 将所有的可能出现的数字放进候选list
        for (int i = min; i <= max; i++) {
            listRandom.add(i);
        }
        // 从候选list中取出放入数组，已经被选中的就从这个list中移除
        for (int i = 0; i < count; i++) {
            int index = getRandom(0, listRandom.size() - 1);
            randoms[i] = listRandom.get(index);
            listRandom.remove(index);
        }
        return randoms;
    }

    @Override
    public List<Map<String, Object>> getWordCloud() {
        int[] randoms = getRandoms(1, 4, 3);
        List<Map<String, Object>> wordClouds = new ArrayList<>();
        for (int k = 0; k < randoms.length; k++) {
            Map<String, Object> map = new HashMap<>(2);
            WordCloud wordCloud = new WordCloud();
            wordCloud.setSystemId(randoms[k]);
            wordCloud = wordCloudMapper.selectWordCloud(wordCloud);
            if (null != wordCloud) {
                map.put("systemId", wordCloud.getSystemId());
                map.put("keyWord", wordCloud.getKeyWord());
                wordClouds.add(map);
            }
        }
        return wordClouds;
    }

}
